

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>prml.markov.particle &mdash; prml  documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../_static/language_data.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../index.html" class="icon icon-home"> prml
          

          
          </a>

          
            
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../prml.html">prml package</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../index.html">prml</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../index.html">Module code</a> &raquo;</li>
        
      <li>prml.markov.particle</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for prml.markov.particle</h1><div class="highlight"><pre>
<span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">scipy.misc</span> <span class="k">import</span> <span class="n">logsumexp</span>
<span class="kn">from</span> <span class="nn">scipy.spatial.distance</span> <span class="k">import</span> <span class="n">cdist</span>
<span class="kn">from</span> <span class="nn">.state_space_model</span> <span class="k">import</span> <span class="n">StateSpaceModel</span>


<div class="viewcode-block" id="Particle"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle">[docs]</a><span class="k">class</span> <span class="nc">Particle</span><span class="p">(</span><span class="n">StateSpaceModel</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    A class to perform particle filtering, smoothing</span>

<span class="sd">    z_1 ~ p(z_1)\n</span>
<span class="sd">    z_n ~ p(z_n|z_n-1)\n</span>
<span class="sd">    x_n ~ p(x_n|z_n)</span>

<span class="sd">    Parameters</span>
<span class="sd">    ----------</span>
<span class="sd">    init_particle : (n_particle, ndim_hidden)</span>
<span class="sd">        initial hidden state</span>
<span class="sd">    sampler : callable (particles)</span>
<span class="sd">        function to sample particles at current step given previous state</span>
<span class="sd">    nll : callable (observation, particles)</span>
<span class="sd">        function to compute negative log likelihood for each particle</span>

<span class="sd">    Attribute</span>
<span class="sd">    ---------</span>
<span class="sd">    hidden_state : list of (n_paticle, ndim_hidden) np.ndarray</span>
<span class="sd">        list of particles</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">init_particle</span><span class="p">,</span> <span class="n">system</span><span class="p">,</span> <span class="n">cov_system</span><span class="p">,</span> <span class="n">nll</span><span class="p">,</span> <span class="n">pdf</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        construct state space model to perform particle filtering or smoothing</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        init_particle : (n_particle, ndim_hidden) np.ndarray</span>
<span class="sd">            initial hidden state</span>
<span class="sd">        system : (ndim_hidden, ndim_hidden) np.ndarray</span>
<span class="sd">            system matrix aka transition matrix</span>
<span class="sd">        cov_system : (ndim_hidden, ndim_hidden) np.ndarray</span>
<span class="sd">            covariance matrix of process noise</span>
<span class="sd">        nll : callable (observation, particles)</span>
<span class="sd">            function to compute negative log likelihood for each particle</span>

<span class="sd">        Attribute</span>
<span class="sd">        ---------</span>
<span class="sd">        particle : list of (n_paticle, ndim_hidden) np.ndarray</span>
<span class="sd">            list of particles at each step</span>
<span class="sd">        weight : list of (n_particle,) np.ndarray</span>
<span class="sd">            list of importance of each particle at each step</span>
<span class="sd">        n_particle : int</span>
<span class="sd">            number of particles at each step</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">particle</span> <span class="o">=</span> <span class="p">[</span><span class="n">init_particle</span><span class="p">]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">ndim_hidden</span> <span class="o">=</span> <span class="n">init_particle</span><span class="o">.</span><span class="n">shape</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">weight</span> <span class="o">=</span> <span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">)</span> <span class="o">/</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">system</span> <span class="o">=</span> <span class="n">system</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">cov_system</span> <span class="o">=</span> <span class="n">cov_system</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">nll</span> <span class="o">=</span> <span class="n">nll</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>

<div class="viewcode-block" id="Particle.resample"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.resample">[docs]</a>    <span class="k">def</span> <span class="nf">resample</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">index</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">,</span> <span class="n">p</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="n">index</span><span class="p">]</span></div>

<div class="viewcode-block" id="Particle.predict"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.predict">[docs]</a>    <span class="k">def</span> <span class="nf">predict</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">predicted</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">resample</span><span class="p">()</span> <span class="o">@</span> <span class="bp">self</span><span class="o">.</span><span class="n">system</span><span class="o">.</span><span class="n">T</span>
        <span class="n">predicted</span> <span class="o">+=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">multivariate_normal</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">ndim_hidden</span><span class="p">),</span> <span class="bp">self</span><span class="o">.</span><span class="n">cov_system</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">predicted</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">)</span> <span class="o">/</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">predicted</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span></div>

<div class="viewcode-block" id="Particle.weigh"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.weigh">[docs]</a>    <span class="k">def</span> <span class="nf">weigh</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">observed</span><span class="p">):</span>
        <span class="n">logit</span> <span class="o">=</span> <span class="o">-</span><span class="bp">self</span><span class="o">.</span><span class="n">nll</span><span class="p">(</span><span class="n">observed</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
        <span class="n">logit</span> <span class="o">-=</span> <span class="n">logsumexp</span><span class="p">(</span><span class="n">logit</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">logit</span><span class="p">)</span></div>

<div class="viewcode-block" id="Particle.filter"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.filter">[docs]</a>    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">observed</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">weigh</span><span class="p">(</span><span class="n">observed</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span></div>

<div class="viewcode-block" id="Particle.filtering"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.filtering">[docs]</a>    <span class="k">def</span> <span class="nf">filtering</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">observed_sequence</span><span class="p">):</span>
        <span class="n">mean</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">cov</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">obs</span> <span class="ow">in</span> <span class="n">observed_sequence</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">predict</span><span class="p">()</span>
            <span class="n">p</span><span class="p">,</span> <span class="n">w</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">obs</span><span class="p">)</span>
            <span class="n">mean</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">average</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">weights</span><span class="o">=</span><span class="n">w</span><span class="p">))</span>
            <span class="n">cov</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">cov</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">rowvar</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">aweights</span><span class="o">=</span><span class="n">w</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">mean</span><span class="p">),</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">cov</span><span class="p">)</span></div>

<div class="viewcode-block" id="Particle.transition_probability"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.transition_probability">[docs]</a>    <span class="k">def</span> <span class="nf">transition_probability</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">particle</span><span class="p">,</span> <span class="n">particle_prev</span><span class="p">):</span>
        <span class="n">dist</span> <span class="o">=</span> <span class="n">cdist</span><span class="p">(</span>
            <span class="n">particle</span><span class="p">,</span>
            <span class="n">particle_prev</span> <span class="o">@</span> <span class="bp">self</span><span class="o">.</span><span class="n">system</span><span class="o">.</span><span class="n">T</span><span class="p">,</span>
            <span class="s2">&quot;mahalanobis&quot;</span><span class="p">,</span>
            <span class="n">VI</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cov_system</span><span class="p">))</span>
        <span class="n">matrix</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="mf">0.5</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">square</span><span class="p">(</span><span class="n">dist</span><span class="p">))</span>
        <span class="n">matrix</span> <span class="o">/=</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">matrix</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="n">matrix</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">matrix</span><span class="p">)]</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">/</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_particle</span>
        <span class="k">return</span> <span class="n">matrix</span></div>

<div class="viewcode-block" id="Particle.smooth"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.smooth">[docs]</a>    <span class="k">def</span> <span class="nf">smooth</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">particle_next</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span><span class="p">]</span>
        <span class="n">weight_next</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span><span class="p">]</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span> <span class="o">-=</span> <span class="mi">1</span>
        <span class="n">particle</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span><span class="p">]</span>
        <span class="n">weight</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span><span class="p">]</span>
        <span class="n">matrix</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">transition_probability</span><span class="p">(</span><span class="n">particle_next</span><span class="p">,</span> <span class="n">particle</span><span class="p">)</span><span class="o">.</span><span class="n">T</span>
        <span class="n">weight</span> <span class="o">*=</span> <span class="n">matrix</span> <span class="o">@</span> <span class="n">weight_next</span> <span class="o">/</span> <span class="p">(</span><span class="n">weight</span> <span class="o">@</span> <span class="n">matrix</span><span class="p">)</span>
        <span class="n">weight</span> <span class="o">/=</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">weight</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></div>

<div class="viewcode-block" id="Particle.smoothing"><a class="viewcode-back" href="../../../prml.markov.html#prml.markov.particle.Particle.smoothing">[docs]</a>    <span class="k">def</span> <span class="nf">smoothing</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">observed_sequence</span><span class="p">:</span><span class="n">np</span><span class="o">.</span><span class="n">ndarray</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">observed_sequence</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">filtering</span><span class="p">(</span><span class="n">observed_sequence</span><span class="p">)</span>
        <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">smoothed_until</span> <span class="o">!=</span> <span class="o">-</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">smooth</span><span class="p">()</span>
        <span class="n">mean</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">cov</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">p</span><span class="p">,</span> <span class="n">w</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">particle</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">):</span>
            <span class="n">mean</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">average</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">weights</span><span class="o">=</span><span class="n">w</span><span class="p">))</span>
            <span class="n">cov</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">cov</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">rowvar</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">aweights</span><span class="o">=</span><span class="n">w</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">mean</span><span class="p">),</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">cov</span><span class="p">)</span></div></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2019, Author

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>